import { createRouter, createWebHistory } from 'vue-router'
import MapView from '../views/Map/MapView.vue'
import LoginView from '../views/Login/LoginView.vue'
import NotFound from '@/components/NotFound.vue'



const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      alias: '/',
      component: LoginView
    },
    {
      path: '/map',
      name: 'map',
      component: MapView
    },
    /* Not Found */
    { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }
  ]
})

router.beforeEach(async (to, from, next) => {
  const auth = localStorage.getItem('token')
  if (to.path == '/login') {
    if (auth) {
      router.push('/map')
    } else {
      next()
    }
  } else {
    if (auth) {
      next()
    } else {
      router.push('/login')
    }
  }
})

export default router
